package main

import (
	"context"
	"fmt"
	"log"
	"sync"
	"time"
	common "user_service/config"
	"user_service/domain"
	"user_service/initialize"
	"user_service/repository"
)

func main() {
	CreateUser()
	//getMaxId()
}

// CreateUser 测试并发创建用户
func CreateUser() {

	mockUser := &domain.User{
		Name:     "Test",
		Email:    "test@gmail.com",
		Password: "password",
	}

	app := initialize.App()
	// 指定数据库名
	db := app.Mongo.Database(common.Configs.DB.Name)

	defer app.CloseDBConnection()

	// 初始化Repository
	r := repository.NewUserRepository(db)
	cr := repository.NewCounterRepository(db)
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			err := func() error {
				maxValue, err := cr.NextCounterValue(context.Background(), domain.CollectionUser)
				mockUser.Id = maxValue
				err = r.Create(context.TODO(), mockUser)
				if err != nil {
					log.Fatalln(err)
				}
				// 获取当前时间
				now := time.Now()
				// 格式化时间，精确到毫秒
				formattedTime := now.Format("2006-01-02 15:04:05.000")
				fmt.Println(formattedTime)
				wg.Done()
				return nil
			}()
			if err != nil {
			}
		}()
	}
	wg.Wait()
}

// 测试获取最大ID
func getMaxId() {
	app := initialize.App()
	// 指定数据库名
	db := app.Mongo.Database(common.Configs.DB.Name)
	defer app.CloseDBConnection()
	cr := repository.NewCounterRepository(db)
	var wg sync.WaitGroup
	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() error {
			maxValue, err := cr.NextCounterValue(context.Background(), domain.CollectionUser)
			if err != nil {
				//log.Fatalln(err)
			}
			// 获取当前时间
			now := time.Now()
			// 格式化时间，精确到毫秒
			formattedTime := now.Format("2006-01-02 15:04:05.000")
			fmt.Println(formattedTime, maxValue)
			wg.Done()
			return nil
		}()
	}
	wg.Wait()
}
